package com.soboot.datasource.intercptor;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.extension.handlers.AbstractSqlParserHandler;
import com.soboot.base.constant.BaseConstant;
import com.soboot.base.model.BaseDataScope;
import com.soboot.base.model.BaseRole;
import com.soboot.base.model.BaseUser;
import com.soboot.base.util.SecurityUtil;
import com.soboot.datasource.annotation.DataScope;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;

import java.sql.Connection;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * @Author:
 * @createTime: 2022年09月19日 15:29:40
 * @version: 1.0
 * @Description: 数据权限拦截器
 * @Copyright:
 */
@Slf4j
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class DataScopeInterceptor extends AbstractSqlParserHandler implements Interceptor {

    @Override
    @SneakyThrows
    public Object intercept(Invocation invocation) {
        StatementHandler statementHandler = (StatementHandler) PluginUtils.realTarget(invocation.getTarget());
        MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
        this.sqlParser(metaObject);
        // 先判断是不是SELECT操作
        MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
        if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) {
            return invocation.proceed();
        }

        BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
        String originalSql = boundSql.getSql();
        Object parameterObject = boundSql.getParameterObject();

        //查找参数中包含DataScope类型的参数
        BaseDataScope dataScope = findDataScopeObject(parameterObject);

        if (dataScope != null) {
            // 获取当前的用户
            BaseUser currentUser = SecurityUtil.getDataUser();
            if (null != currentUser) {
                // 如果是超级管理员，则不过滤数据
                if (!currentUser.isAdmin()) {
                    String sqlString = dataScopeFilter(currentUser, dataScope);
                    if (StrUtil.isNotBlank(sqlString)) {
                        originalSql = "SELECT * FROM (" + originalSql + ") TEMP_DATA_SCOPE WHERE 1=1 AND (" + sqlString.substring(4) + ")";
                        metaObject.setValue("delegate.boundSql.sql", originalSql);
                    }
                }
            }
        }
        return invocation.proceed();
    }

    /**
     * 数据范围过滤
     *
     * @param user
     * @param dataScope
     */
    private String dataScopeFilter(BaseUser user, BaseDataScope dataScope) {
        StringBuilder sqlString = new StringBuilder();
        List<BaseRole> roles = user.getRoles();
        if (CollUtil.isNotEmpty(roles)){
            for (BaseRole role : roles){
                String roleDataScope = role.getDataScope();
                if (BaseConstant.DataScope.ALL.getKey().equals(roleDataScope)) {
                    sqlString = new StringBuilder();
                    break;
                } else if (BaseConstant.DataScope.CUSTOM.getKey().equals(roleDataScope)) {
                    sqlString.append(StrUtil.format(
                            " OR {} IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) "
                            ,dataScope.getDeptScopeName()
                            ,"'" + role.getId() + "'"
                    ));
                } else if (BaseConstant.DataScope.DEPT.getKey().equals(roleDataScope)) {
                    sqlString.append(StrUtil.format(
                            " OR {} = {} "
                            ,dataScope.getDeptScopeName()
                            ,"'" + user.getDeptName() + "'"
                    ));
                } else if (BaseConstant.DataScope.DEPTANDCHILD.getKey().equals(roleDataScope)) {
                    sqlString.append(StrUtil.format(
                            " OR {} IN ( SELECT descendant FROM sys_dept_relation WHERE ancestor = {} )"
                            ,dataScope.getDeptScopeName()
                            ,"'" + user.getDeptName() + "'"
                    ));
                } else if (BaseConstant.DataScope.SELF.getKey().equals(roleDataScope)) {
                    sqlString.append(StrUtil.format(" OR {} = {} "
                            ,dataScope.getUserScopeName()
                            ,"'" + user.getId() + "'"
                    ));
                }
            }
        }
        log.info("数据范围过滤:{}", sqlString);
        return sqlString.toString();
    }

    /**
     * 生成拦截对象的代理
     *
     * @param target 目标对象
     * @return 代理对象
     */
    @Override
    public Object plugin(Object target) {
        if (target instanceof StatementHandler) {
            return Plugin.wrap(target, this);
        }
        return target;
    }

    /**
     * mybatis配置的属性
     *
     * @param properties mybatis配置的属性
     */
    @Override
    public void setProperties(Properties properties) {

    }

    /**
     * 查找参数是否包括DataScope对象
     *
     * @param parameterObj 参数列表
     * @return DataScope
     */
    private BaseDataScope findDataScopeObject(Object parameterObj) {
        if (parameterObj instanceof BaseDataScope) {
            return (BaseDataScope) parameterObj;
        } else if (parameterObj instanceof Map) {
            for (Object val : ((Map<?, ?>) parameterObj).values()) {
                if (val instanceof BaseDataScope) {
                    return (BaseDataScope) val;
                }
            }
        }
        return null;
    }

}
